package addressBook

import (
	"apiExample/auth"
	"apiExample/common"
	"errors"
	"fmt"
)

type Photo struct {
	MediaId string `json:"media_id"`
}

type Phone struct {
	Type string `json:"type"`
	Number string `json:"number"`
}

type Extend struct {
	Name string `json:"name"`
	Value string `json:"value"`
}

type UserInfo struct {
	UserId string `json:"userid"`
	Name string `json:"name"`
	Alias string `json:"alias"`
	Account string `json:"account"`
	Sex string `json:"sex"`
	Photo *Photo `json:"photo"`
	DepartmentId []string `json:"department_id"`
	Position string `json:"position"`
	EmployeeId string `json:"employee_id"`
	Address string `json:"address"`
	Phone []*Phone `json:"phone"`
	Extend []*Extend `json:"extend"`
}

type userResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	User *UserInfo `json:"user"`
}

func commonGetUser(url string) (*UserInfo, error) {
	r := &userResult{}
	if err := common.HttpGetData(url, r); err != nil {
		return nil, err
	}

	if r.Result != 0 {
		return nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", r.Result, r.Errmsg))
	}
	return  r.User, nil
}
/*
	3.1 获取口袋助理用户信息
*/
func GetUserInfoByCode(code string) (*UserInfo, error) {

	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/user/get?access_token=%s&code=%s&detail=0", common.ApiUrl, token, code)

	return commonGetUser(url)
}

/*
	4.2.1 获取用户
*/
func GetUserInfoById(userId string) (*UserInfo, error) {

	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/user/get?access_token=%s&userid=%s", common.ApiUrl, token, userId)

	return commonGetUser(url)
}
/*
	4.2.1 获取用户
 */
func GetUserInfoByAlias(alias string) (*UserInfo, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/roster/user/get?access_token=%s&alias=%s", common.ApiUrl, token, alias)

	return commonGetUser(url)
}